//
//  WeatherDesktopPref.h
//  WeatherDesktop
//
//  Created by Justin Dell on 11/7/08.
//  Copyright (c) 2008 . All rights reserved.
//

#import "WeatherDesktopPref.h"

BOOL running;
static NSString* enginePath = @"/Users/Shared/WeatherDesktop/WeatherDesktop Engine";

@implementation WeatherDesktopPref

// -------------------------------------------------------------------------------
//	startEngineWithZip andRefresh
//
//  starts the WeatherDesktop engine and updates the defaults
// -------------------------------------------------------------------------------
-(void)startEngineWithZip:(NSString *)zip andRefresh:(NSString *)refresh {
    engine = [[NSTask alloc] init];
    NSMutableArray *args = [NSMutableArray array];
    [args addObject:zip];
    [args addObject:refresh];
    [engine setLaunchPath:enginePath];
    [engine setArguments:args];
    [engine launch];
    [[NSUserDefaults standardUserDefaults] 
#warning 64BIT: Check formatting arguments
        setObject:[NSString stringWithFormat:@"%d", [engine processIdentifier]] 
        forKey:@"process"];
}

// -------------------------------------------------------------------------------
//	initWithBundle:bundle
//
//	The preference pane is being initialized, remember our bundle ID for later.
// -------------------------------------------------------------------------------
-(id)initWithBundle:(NSBundle*)bundle {
	if ((self = [super initWithBundle:bundle]) != nil) {
		
        // Check for already existing process 
        NSUserDefaults* standardUserDefaults = [NSUserDefaults standardUserDefaults];
		NSString* strValue = [standardUserDefaults objectForKey:@"zipField"];
        NSString* refValue = [standardUserDefaults objectForKey:@"refreshField"];
        NSString* processValue = [standardUserDefaults objectForKey:@"process"];
		if ((processValue != nil)&&(kill((pid_t)[processValue integerValue], SIGKILL) != -1)) {
            running = YES;
            [self startEngineWithZip:strValue andRefresh:refValue];
        }
        else {
            running = NO;
        }
	}
	
	return self;
}

// -------------------------------------------------------------------------------
//	mainViewDidLoad
//
//  mainViewDidLoad is invoked by the default implementation of loadMainView
//  after the main nib file has been loaded and the main view of the preference
//  pane has been set.  The default implementation does nothing.  Override
//  this method to perform any setup that must be performed after the main
//  nib file has been loaded and the main view has been set.
// -------------------------------------------------------------------------------
- (void)mainViewDidLoad {
	NSUserDefaults* standardUserDefaults = [NSUserDefaults standardUserDefaults];
	if (standardUserDefaults) {
		NSString* strValue = [standardUserDefaults objectForKey:@"zipField"];
        NSString* refValue = [standardUserDefaults objectForKey:@"refreshField"];
		if (strValue != nil) [zipField setStringValue: strValue];
        if (refValue != nil) [refreshField setStringValue: refValue];
	}
    if (running) {
        [start setTitle:@"Stop WeatherDesktop"];
    }
    else {
        [start setTitle:@"Start WeatherDesktop"];
    }
}

// -------------------------------------------------------------------------------
//	restartEngine:
//
//	This method kills and restarts the Weather Engine
// -------------------------------------------------------------------------------
-(void)restartEngine {
    [engine terminate];
    [engine release];
    [self startEngineWithZip:[zipField stringValue] andRefresh:[refreshField stringValue]];
    running = YES;
}

// -------------------------------------------------------------------------------
//	mainNibName
//
//  mainNibName is invoked by the default implementation of loadMainView.
//
//  The default implementation returns the value of the NSMainNibFile key
//  in the bundle's Info plist. You can override this if you want to
//  dynamically select the main nib file for this preference.
//
//  The value returned must NOT include the ".nib" extension.
// -------------------------------------------------------------------------------
- (NSString*)mainNibName {
	// here you can decide to use an alternate nib file for different
	// system versions if you are so inclinded, but in our case we use one nib,
	// and two alternate views to present our UI.
	//
	return @"WeatherDesktopPref";
}

// -------------------------------------------------------------------------------
//	toggleStart:
//
//	This method is called when the start button is clicked
// -------------------------------------------------------------------------------
- (IBAction)toggleStart:(id)sender {
    if (running) {
        [engine terminate];
        [engine release]; 
        [start setTitle:@"Start WeatherDesktop"];
        running = NO;
    }
    else {
        [self startEngineWithZip:[zipField stringValue] andRefresh:[refreshField stringValue]];
        [start setTitle:@"Stop WeatherDesktop"];
        running = YES;
    }
}

// -------------------------------------------------------------------------------
//	editfieldAction:
//
//	This method is called when editing is committed/finished in our edit field.
// -------------------------------------------------------------------------------
- (IBAction)editfieldAction:(id)sender {
	// store the current edit field value to our user defaults
	[[NSUserDefaults standardUserDefaults] setObject:[sender stringValue] forKey:@"zipField"];
    if (running) [self restartEngine];
}

// -------------------------------------------------------------------------------
//	editRefreshAction:
//
//	This method is called when editing is committed/finished in our refresh field.
// -------------------------------------------------------------------------------
- (IBAction)editRefreshAction:(id)sender {
	// store the current edit field value to our user defaults
	[[NSUserDefaults standardUserDefaults] setObject:[sender stringValue] forKey:@"refreshField"];
    if (running) [self restartEngine];
}

#pragma mark - delegate methods

// -------------------------------------------------------------------------------
//	confirmSheetDidEnd:sheet:returnCode:contextInfo
// -------------------------------------------------------------------------------
- (void)confirmSheetDidEnd:(NSWindow*)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
	[sheet orderOut:self];	// hide the sheet

	// decide how we want to unselect
	if (returnCode == NSAlertDefaultReturn)
		[self replyToShouldUnselect:NSUnselectNow];
	else
		[self replyToShouldUnselect:NSUnselectCancel];
}

@end
